package mylibrary.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.Timestamp;

public class Class1 {

	public static void main(String[] args) throws Exception {
		
		Class1 class1 = new Class1();
		
		System.out.println(new Timestamp(System.currentTimeMillis()));
		//class1.copyFile("D:\\Study\\EJB.pdf", "c:\\ejb.pdf");
		class1.copyFile("D:\\Study\\axis2-1.5.5-bin.zip", "c:\\axis2-1.5.5-bin.zip");
		System.out.println(new Timestamp(System.currentTimeMillis()));
		
	}
	
	
	public void readFile(String filePath) throws Exception {
		
		FileInputStream in = new FileInputStream(filePath);
		
		FileChannel fc = in.getChannel();
		
		ByteBuffer buf = ByteBuffer.allocate(1024);
		
		fc.read(buf);
	}
	
	/**
	 * clear() 方法重设缓冲区，使它可以接受读入的数据。 flip() 方法让缓冲区可以将新读入的数据写入另一个通道。
	 * @param sourceFile
	 * @param destinationFile
	 * @throws Exception
	 */
	public void copyFile(String sourceFile, String destinationFile) throws Exception {

		FileInputStream in = new FileInputStream(sourceFile);
		FileChannel fcin = in.getChannel();
		
		
		FileOutputStream out = new FileOutputStream(destinationFile);
		FileChannel fcout = out.getChannel();
		
		ByteBuffer buf = ByteBuffer.allocate(1024);
		
		while(fcin.read(buf) != -1) {
			
			buf.flip();
			
			fcout.write(buf);
			
			buf.clear();
		}
		
		in.close();
		out.close();
	}
	
	public void copyFile_old(String sourceFile, String destinationFile) throws Exception {
		FileInputStream   fis   =   new   FileInputStream(sourceFile); 
		FileOutputStream   fos   =   new   FileOutputStream(destinationFile); 
		byte[]   buff   =   new   byte[1024]; 
		int   readed   =   -1; 
		while((readed   =   fis.read(buff))   >   0) 
		    fos.write(buff,   0,   readed); 
		fis.close(); 
		fos.close();
	}
}
